package cn.edik.plugin.dubbo.core;

import com.jfinal.kit.Prop;
import com.jfinal.kit.PropKit;
import com.jfinal.kit.StrKit;
import com.jfinal.plugin.IPlugin;
import org.apache.dubbo.config.ProtocolConfig;

import java.io.IOException;

/**
 * Author    : edik
 * CreateTime: 2019-02-14 14:41
 **/
public class DubboPlugin implements IPlugin {

    private Prop prop;

    /**
     * 使用无参构造，使用jfinal.properties作为你的配置文件名，可以更便捷的使用dubbo容器功能
     *
     * @param fileName
     */
    @Deprecated
    public DubboPlugin(String fileName) {
        if (StrKit.notBlank(fileName)) {
            prop = PropKit.use(fileName);
        } else {
            prop = getDefalutProp();
        }
    }

    public DubboPlugin(Prop prop) {
        this.prop = prop;
    }

    public DubboPlugin() {
        prop = getDefalutProp();
    }

    private Prop getDefalutProp() {
        return PropKit.use("jfinal-dubbo.properties");
    }

    @Override
    public boolean start() {
        JFinalDubbo.init(prop);
        try {
            JFinalDubbo.scanServices();
            return true;
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (InstantiationException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return false;
    }

    @Override
    public boolean stop() {
        ProtocolConfig protocolConfig = new ProtocolConfig();
        protocolConfig.destroy();
        return true;
    }


}
